import requests
import json
import os
import time

# BaseUrl = "http://localhost:8870/"
BaseUrl = "http://aiapi.liveshop.vip/"
strToken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiaWF0IjoxNzAwMjM4MTc3LCJleHAiOjE3MDI4MzAxNzd9.ITkJk0Z7iKe13kCcc-oMkS8c0SFm2F4avoEM9f-50Ac0IcZBX1OZs0z2RHel9G9alGat6dlVCJzSZXkpIYfj4w"
# 上传图片
def upload_image_with_parameters(image_path, url, parameters):
    try:
        headers = {
            # 'Accept': 'application/json, text/plain, */*',
            # 'accept-encoding': 'gzip, deflate, br',
            "token": strToken
        }
        # Open the image file in binary mode
        with open(image_path, 'rb') as image_file:
            # Prepare the files dictionary for the image upload
            files = {'file': (image_file.name, image_file, 'image/jpeg')}
            # Send a POST request with the image and parameters
            response = requests.post(url, files=files, data=parameters, headers=headers)

            # Check if the request was successful
            if response.status_code == 200:
                print("Image upload successful!")
                print("Response:", response.text)
                return response.text
            else:
                print("Image upload failed. Status code:", response.status_code)
    except Exception as e:
        print("An error occurred:", str(e))


# 获取服务器的页面数据
def send_request(url, data, type='get'):
    try:
        headers = {
            # 'Accept': 'application/json, text/plain, */*',
            # 'accept-encoding': 'gzip, deflate, br',
            "token": strToken
        }
        if type == 'get':
            respose = requests.get(url, json=data, headers=headers, timeout=10)
        else :
            respose = requests.post(url, json=data, headers=headers, timeout=10)
        respose.encoding = 'utf-8'
        if respose.status_code == 200:
            return respose.text
    except Exception as e:
        print('获取网页数据异常：'+str(e))
        return None


def login():# 定义POST请求的URL和要发送的参数
    url = BaseUrl+"user/login"  # 替换为实际的URL
    data = {"username": "shouhulife", "pwd": "123456"}  # 替换为实际的参数

    # 发送POST请求
    response = send_request(url, data, type='post')
    print(response)


def register(name):
    # 定义POST请求的URL和要发送的参数
    url = BaseUrl+"user/register"  # 替换为实际的URL
    data = {"username": name, "pwd": "123456"}  # 替换为实际的参数

    # 发送POST请求
    response = send_request(url, data, type='post')
    print(response)


def getWenZhangList():
    # 定义POST请求的URL和要发送的参数
    # url = BaseUrl+"article/allListFree"  # 获取列表
    url = BaseUrl+"article/idFree"  # 获取文章
    # data = {"page": "1", "size": "2"}  # 替换为实际的参数
    data = {"id": "1"}  # 替换为实际的参数

    # 发送POST请求
    response = send_request(url, data, type='get')
    print(response)


# 上传图片
def upload_file(image_path, type_str='article'):
    # image_path = 'd:/aaa.png'
    upload_url = BaseUrl+'file/upload'
    # Replace 'parameter1' and 'parameter2' with the parameter names and their values
    parameters = {
        'type': type_str,
    }
    return upload_image_with_parameters(image_path, upload_url, parameters)


def add_banner():
    url = BaseUrl + "banner/add"
    imgUrl = upload_file(r"C:\Users\Administrator\Desktop\bb.png", "goods")
    print(imgUrl)
    datas = json.loads(imgUrl)
    print(datas["data"])
    data = {"img": datas["data"], "url": "www.baidu.com", "type": 1, "px": 1}  # 替换为实际的参数

    # 发送POST请求
    response = send_request(url, data, type='post')
    print(response)


# 添加文章
def add_article(title, content, base_dir, type):
    # base_dir = r"E:\sd\stable-diffusion-webui-master\outputs\txt2img-images\2023-08-11"
    url = BaseUrl+"article/add"  # 获取文章
    # title = "魔女勾心"
    # content = "魔女的外貌通常被描绘为神秘、令人着迷，有时也会带有一些恐怖或阴暗的元素。"
    imgs = []

    # 获取当前目录下的所有文件
    files = [os.path.join(base_dir, file) for file in os.listdir(base_dir)]
    # 遍历文件列表，输出文件名
    for file in files:
        # print(file)
        try:
            imgUrl = upload_file(file)
            print(imgUrl)
            datas = json.loads(imgUrl)
            print(datas["data"])
            imgs.append(datas["data"])
        except Exception as e:
            print("上传图片出错。"+e)

    print(imgs)
    data = {"title": title, "content": content, "type": type, "imgs": json.dumps(imgs)}  # 替换为实际的参数

    # 发送POST请求
    response = send_request(url, data, type='post')
    print(response)


def add_art():
    base_dir = r"C:\Users\Administrator\Desktop\create\app\img"
    title = "有肉肉的小美女"
    contet = "玩球"
    # 美女 新时代 二次元 写真
    type = "写真"
    add_article(title, contet, base_dir, type)


if __name__ == "__main__":
    # 登录更新token
    # login()
    # register("shouhulife70")


    # 上传图片 goods 商品
    # file = r"C:\Users\Administrator\Desktop\a2.png"
    # imgUrl = upload_file(file, 'goods')
    # print(imgUrl)
    # 发布一篇文章
    # add_art()

    # 发布一个banner
    # add_banner()
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

    # imgUrl = upload_file(r"C:\Users\Administrator\Desktop\12.png", "goods")
    # print(imgUrl)
